/*
 * Copyright 2008 aileron.cc, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package cc.aileron.commons.string;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cc.aileron.commons.utility.Quote;

/**
 * String 拡張
 * @author Aileron
 *
 */
public class StringExtension
{
    /**
     * 拡張 String インスタンスの生成
     * @param string
     */
    public static StringExtension stringExtension(final String string)
    {
        return new StringExtension(string);
    }
    
    /**
     * String
     */
    private final String string ;
    
    /**
     * String　拡張
     * @param string
     */
    public StringExtension(final String string)
    {
        this.string = string;
    }
    
    /*
     * (非 Javadoc)
     * @see java.lang.Object#toString()
     */
    public String toString()
    {
        return this.string;
    }
    
    /**
     * アンダースコア or バー　区切り
     */
    private static final Pattern underscore = Pattern.compile("[_-](.)");
    
    /**
     * 文字列の変換
     * @param value
     * @return
     */
    public StringExtension toCamel()
    {
        final String value = this.string;
        
        final StringBuilder builder = new StringBuilder();
        final Matcher matcher = underscore.matcher(value);
        
        int i = 0;
        while(matcher.find())
        {
            builder.append( value.subSequence(i, matcher.start()) );
            builder.append( matcher.group(1).toUpperCase() );
            i = matcher.end();
        }
        builder.append( value.subSequence(i, value.length()) );
        
        return stringExtension(builder.toString());
    }
    
    /**
     * toCapitalize
     * @return
     */
    public StringExtension toCapitalize()
    {
        return stringExtension(this.string.substring(0, 1).toUpperCase() + this.string.substring(1));
    }

    /**
     * Htmlエスケープ
     * @return
     */
    public StringExtension toHtmlEscape()
    {
        return stringExtension(
                Quote.htmlMultibyteQuote(this.string)
                    .replace("\r\n", "<br />")
                    .replace("\r", "<br />")
                    .replace("\n", "<br />")
        );
    }
}